<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <link rel="stylesheet" href="/resources/css/formSelects-v4.css"/>
    <link rel="stylesheet" href="/resources/layui/css/layui.css">
    <script rel="stylesheet" src="/resources/layui/layui.js"></script>
    <script rel="stylesheet" src="/resources/js/jquery.min.js"></script>

    <link rel="stylesheet" href="/resources/css/metroStyle/metroStyle.css">
    <script src="/resources/js/jquery.ztree.all.js"></script>
    <script src="/resources/js/function/Local.js"></script>
    <script src="/resources/js/function/Session.js"></script>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row">
        <div class="layui-col-sm8">
            <table id="demo" lay-filter="test"></table>
        </div>
        <div class="layui-col-sm3 layui-col-sm-offset1">
            <h2>显示所有的权限</h2>
            <hr>
            <ul id="treeDemo" class="ztree"></ul>
            <hr>
            <button class="layui-btn" style="width: 100%;" onclick="assignPerms();">授权</button>
        </div>
    </div>
</div>
</body>
</html>
<script>
    var table,form,layer,laytpl;
    layui.config({
        base: '/resources/js/'
    }).extend({
        formSelects: 'formSelects-v4'
    });
    layui.use(['table','form','formSelects','laytpl','layer'], function(){
        table = layui.table;
        form=layui.form;
        layer=layui.layer;
        laytpl=layui.laytpl;
        table.on('radio(test)', function(obj){
            roleId = obj.data.id;
            loadPerTree(obj.data.id);
        });
        //第一个实例
        table.render({
            elem: '#demo'
            ,url: new Local().base_url+'/role/show' //数据接口
            ,page: true //开启分页
            ,even : true
            ,toolbar:"#toolbarDemo"
            ,id : "demo"
            ,cols: [[ //表头
                {field:'id',type:'radio'}
                ,{field: 'id', title: 'ID'}
                ,{field: 'name', title: '角色名称'}
                /*,{field: 'zhuangtai', title: '状态',templet:function(d){
                        var str='禁用';
                        if(d.zhuangtai==1){
                            str="未禁用";
                        }
                        return str;
                }}*/
                ,{title:'操作',toolbar: '#barDemo'}
            ]]
        });

        table.on('tool(test)',function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            switch(layEvent){
                case "list":
                    $.get('add.html',function (s) {
                        //parent
                        layer.open({
                            type : 1,
                            title : '查看角色',
                            area:'70%',
                            content:s,
                            btn : ['确定','取消'],
                            success:function(){
                                $("#name").val(data.name).attr("readonly",true);
                                $("#zhuangtai").attr("checked",data.zhuangtai==1).attr("readonly",true);
                                form.render();
                            }
                            ,yes:function(){
                                layer.close(layer.index);
                                layer.msg("请不要随意修改!");
                            }
                        });
                    });
                    break;
            }
        });
        table.on('toolbar(test)', function(obj) {
            switch (obj.event) {
                case 'add':
                    $.get('add.html',function (s) {
                        //parent
                        layer.open({
                            type : 1,
                            title : '添加角色',
                            area:'70%',
                            content:s,
                            btn : ['确定','取消'],
                            success:function(){
                                form.render();
                            }
                            ,yes:function(){
                                var str = $("#form").serialize();
                                $.post(new Local().base_url+"/role/add",str,function(data){
                                    layer.close(layer.index);
                                    table.reload('demo');
                                    layer.msg("添加成功!");
                                });
                            }
                        });
                    });
                    break;
            }
        });

    });
</script>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon layui-icon-add-circle"></i> 添加</button>
    </div>
</script>
<script type="text/html" id="barDemo">
    <a href="javascript:void(0)" lay-event="list"><i class="layui-icon layui-icon-list"></i></a>
</script>

<script language="JavaScript">
    var zTreeObj;
    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
    var setting = {
        check : {
            enable : true
        }
    };
    $(function(){
        $.get(new Local().base_url+"/perm/all",function (d) {
            var zhi=d.data;
            console.log(zhi);
            for(let first of zhi){
                first['open'] = true;
                for(let second of first.children){
                    second.open = true;
                }
            }
            zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zhi);
        });
    });
    var roleId; //选中的角色编号
    /**
     * 给角色授权
     */
    function assignPerms() {
        //选中的复选框
        var check = zTreeObj.getCheckedNodes();
        console.log(check);
        var data={
            id:roleId,
            idstr:""
        };
        $.each(check,function(a){
            data.idstr+=this.id+",";
        });
        $.post(new Local().base_url+"/perm/update",data,function(d) {
            layer.msg("角色授权成功！",function(){
                var shujv = JSON.parse(sessionStorage.getItem(new Session().user_login));
                sessionStorage.setItem(new Session().user_login,null);
                sessionStorage.setItem(new Session().user_perms,null);
                if(shujv.role.id==roleId){
                    layer.msg("修改了本角色权限,请重新登录!",function(){
                        top.location='/html/login/login.html';
                    });
                }
            });
        });
    }
    function loadPerTree(roleId){
        $.get(new Local().base_url+"/perm/show/"+roleId,function(d){
            $.get(new Local().base_url+"/perm/all",b=>{
                for(let one of b.data){
                    //判断数组中是否有存在的值
                    one.open=true;
                    if($.inArray(one.id,d) != -1){
                        one.checked=true;
                    }
                    for(let two of one.children){
                        two.open=true;
                        if($.inArray(two.id,d) != -1){
                            two.checked=true;
                        }
                        for(let san of two.children){
                            if($.inArray(san.id,d) != -1){
                                san.checked=true;
                            }
                        }
                    }
                }
                zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, b.data);
            })
        });
    }

</script>                        